/**
 * Copyright 1996 self.com.au
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. (http://www.apache.org/licenses/LICENSE-2.0)
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed 
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
 * the specific language governing permissions and limitations under the License.
 *
 * <dhamma-message src="Atisha (11th century Tibetan Buddhist master)">
 * 	The greatest achievement is selflessness. The greatest worth is self-mastery.
 * 	The greatest quality is seeking to serve others. The greatest precept is continual awareness.
 * 	The greatest medicine is the emptiness of everything. The greatest action is not conforming with the worlds ways.
 * 	The greatest magic is transmuting the passions. The greatest generosity is non-attachment.
 * 	The greatest goodness is a peaceful mind. The greatest patience is humility.
 * 	The greatest effort is not concerned with results. The greatest meditation is a mind that lets go.
 * 	The greatest wisdom is seeing through appearances. 
 * </dhamma-message>
 *
 * @author Ashin Wimalajeewa
 *
 * Note, this is a very old runtime library that I have evolved since 1996. I rarely use it
 * now because the Apache Commons project has made it obsolete.
 */
package self.text;

import java.util.ArrayList;
import java.util.List;

final public class PatternMatcherUtils {
	
  private PatternMatcherUtils() {
	// nothing to do.
  }

  static public String replace( String src, String regExPat, Replacement callback ) {
    ArrayList matches = new ArrayList();

    delegate.acquireMatches( src, regExPat, matches );
    StringBuffer source = new StringBuffer( src );
    transformMatches( source, matches, callback );
    return source.toString();
  }

  static private void transformMatches( StringBuffer source, ArrayList matches, Replacement callback ) {
    int offset = 0;
    int max = matches.size();
    for ( int cntr = 0; cntr < max; cntr++ ) {
      MatchResult result = (MatchResult) matches.get( cntr );
      int b = result.beginOffset();
      int e = result.endOffset();
      String entry = result.getEntry();
      source.delete( b + offset, e + offset );
      String toInsert = (String) callback.replace( entry );
      if ( toInsert == null )
      	toInsert = "ERROR";
      source.insert( b + offset, toInsert );
      offset += toInsert.length() - (e-b);
    }
  }

  static public boolean containsMatch( String src, String regExp ) {
    return delegate.containsMatch( src, regExp );
  }

  static public MatcherBundle createMatcherBundle( List regExps ) throws IllegalArgumentException, IllegalStateException {
    return delegate.createMatcherBundle( regExps );
  }

  static public interface PatternMatcher {
    public void acquireMatches( String src, String regExPat, ArrayList matches ) throws IllegalArgumentException, IllegalStateException;
    public boolean containsMatch( String src, String regExp ) throws IllegalArgumentException, IllegalStateException;

    public MatcherBundle createMatcherBundle( List regExps ) throws IllegalArgumentException, IllegalStateException;
  }

  static public interface MatcherBundle {
    public boolean contains( String src ) throws IllegalArgumentException, IllegalStateException;
  }

	static public class MatchResult {
		private int begin, end;
    private String entry;
		public MatchResult( int b, int e, String ent ) {
			begin = b;
			end = e;
      entry = ent;
		}

		public int beginOffset() {
			return begin;
		}

		public int endOffset() {
			return end;
		}

    public String getEntry() {
      return entry;
    }
	}

  final static PatternMatcher delegate;

  static {
    String delegateClassnameAsString;
//    String ver = System.getProperty( "java.version" );
//    int pos = ver.indexOf( '.' );
//    String mainVer = ver.substring( 0, pos + 2 );
//    float verVal = Float.parseFloat( mainVer );
//    if ( verVal < 1.4F )
//      delegateClassnameAsString = "self.text.OroPatternMatcher";
//    else
//      delegateClassnameAsString = "self.text.SunPatternMatcher";
    delegateClassnameAsString = "self.text.OroPatternMatcher";
    try {
      delegate = (PatternMatcher) Class.forName( delegateClassnameAsString ).newInstance();
    } catch ( Exception err ) {
      throw new IllegalStateException( err.getMessage() );
    }
  }
}

/*

  static public String replace( String src, String regExPat, Replacement callback ) {
    ArrayList matches = new ArrayList();

    delegate.acquireMatches( src, regExPat, matches );
    StringBuffer source = new StringBuffer( src );
    transformMatches( source, matches, callback );
    return source.toString();
  }

  static private void transformMatches( StringBuffer source, ArrayList matches, Replacement callback ) {
    int offset = 0;
    int max = matches.size();
    for ( int cntr = 0; cntr < max; cntr++ ) {
      MatchResult result = (MatchResult) matches.get( cntr );
      int b = result.beginOffset();
      int e = result.endOffset();
      String entry = result.getEntry();
      source.delete( b + offset, e + offset );
      String toInsert = (String) callback.replace( entry );
      source.insert( b + offset, toInsert );
      offset += toInsert.length() - (e-b);
    }
  }
  
  // crap:
  static public String replace( String src, String regExPat, Replacement callback ) {
    ArrayList matches = new ArrayList();

    delegate.acquireMatches( src, regExPat, matches );
    StringBuffer source = new StringBuffer( src );
    
    int cntr = 0;
    while ( matches.size() > 1 ) {
      MatchResult result = (MatchResult) matches.get( 0 );
      int b = result.beginOffset();
      int e = result.endOffset();
      String entry = result.getEntry();
      source.delete( b, e );
      String toInsert = (String) callback.replace( entry );
      source.insert( b, toInsert );
      matches.clear();
      delegate.acquireMatches( source.toString(), regExPat, matches );
      System.out.println( cntr + ":" + regExPat );
    }
    return source.toString();
  }
   
   */  